// pages/address/list/index.js
import {reqAddressList,reqDelAddress} from "../../../api/address"
import {swipeCellBehavior} from "@/behavior/swipeCell"
// 获取应用实例
const app = getApp()
Page({
  behaviors: [swipeCellBehavior],
  // 页面的初始数据
  data: {
    addressList: [1, 2, 3],
    // currentOpen:null,
    // swipeList:[]
  },
  // 获取地址列表数据
 async getUserAddressList(){
   const res = await reqAddressList()
  //  console.log(res,'cs')
  this.setData({addressList:res.data})
 },
 async delAddress(event){
  // console.log(event,'css')
  const {id} = event.currentTarget.dataset
 // 询问用户是否确认删除，modalRes：true/false
  const modalRes = await wx.modal({
    content: '您确认删除该收货地址吗 ?'
  })
  if(modalRes){
    await reqDelAddress(id)
    wx.toast({ title: '收货地址删除成功' })
    this.getUserAddressList()
  }
  // console.log(modalRes,'css')
 },

  // 去编辑页面
  toEdit(event) {
    const {id} =  event.currentTarget.dataset
    wx.navigateTo({
      url: `/modules/settingModule/pages/address/add/index?id=${id}`
    })
  },
  // // 打开滑块
  // swipeCellOpen(event){
  //   const instance = this.selectComponent(`#${event.target.id}`)
  //   this.setData({
  //     currentOpen:instance
  //   })
  // },
  // // 点击页面关闭滑块
  // onSwipeCellPage(){
  //   if(this.data.currentOpen) this.data.currentOpen.close()
  //   this.setData({
  //     currentOpen:null
  //   })
  // },
  //更新收货地址
  changeAddress(event){

    // 判断是否从支付页面进入的
    if(this.flag != 1) return
    //点击的收货地址id
    const addressId = event.currentTarget.dataset.id
    // 根据id,找到收货地址
    const selectAddress = this.data.addressList.find(item => item.id === addressId)
    if(selectAddress){
      // 赋值给全局共享的数据
      app.globalData.address = selectAddress
      wx.navigateBack()
    }


  },
  onLoad(options){
    // console.log("收货地址列表",options)
    this.flag= options.flag// 接收传递过来flag挂载到实例上，方便其他页面使用
    this.getUserAddressList()
    const eventChannel = this.getOpenerEventChannel()
    if(eventChannel && eventChannel.on){
      // console.log('eventChannel',eventChannel)
      eventChannel.on('upDateList',(res)=>{
        this.getUserAddressList()
      })
    }
  },
})
